from django.utils import timezone
from rest_framework import status
from rest_framework.decorators import api_view
from rest_framework.response import Response
from .serializers import UserSerializer, UserLoginSerializer
from .models import User


@api_view(['POST'])
def register_user(request):
    serializer = UserSerializer(data=request.data)
    if serializer.is_valid():
        serializer.save()
        return Response({'code': 0, 'message': '操作成功', 'data': None}, status=status.HTTP_201_CREATED)
    return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)


@api_view(['POST'])
def login_user(request):
    serializer = UserLoginSerializer(data=request.data)
    if serializer.is_valid():
        username = serializer.validated_data['username']
        password = serializer.validated_data['password']
        try:
            user = User.objects.get(username=username)
            print(user.password)
        except User.DoesNotExist:
            return Response({'code': 1, 'message': '用户不存在', 'data': None}, status=status.HTTP_404_NOT_FOUND)

        if user.check_password(password):
            user.last_login = timezone.now()
            user.save()
            return Response({'code': 0, 'message': '操作成功', 'data': None})
        else:
            return Response({'code': 1, 'message': '密码错误', 'data': None}, status=status.HTTP_401_UNAUTHORIZED)
    return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
